
<template>
	<div class="sc-form-table" ref="scFormTable">
		<el-table :data="data" ref="table" :key="toggleIndex" border stripe :maxHeight="maxHeight"
			:scrollbar-always-on="scrollbarAlways" :summary-method="getSummaries" :show-summary="showSummary"
			:cellStyle="cellStyle"
			>
			<el-table-column type="index" width="70" align="center" fixed="left" v-if="showIndex">
				<template #header>
					<el-button v-if="showRowAdd" type="primary" icon="el-icon-plus" size="small" circle
						@click="rowAdd"></el-button>
					<slot name="header"></slot>
				</template>
				<template #default="scope">
					<div class="sc-form-table-handle" :class="[isReadMode ? 'sc-button' : '']">
						<span>{{ scope.$index + 1 }}</span>
						<el-button v-if="showRowDel" type="danger" icon="el-icon-delete" size="small" plain circle
							@click="rowDel(scope.row, scope.$index)"></el-button>
						<slot name="rowDel" :scope="scope"></slot>
					</div>
				</template>
			</el-table-column>
			<el-table-column label width="58" v-if="dragSort">
				<template #default>
					<el-tag class="move" style="cursor: move">
						<el-icon-d-caret style="width: 1em; height: 1em" />
					</el-tag>
				</template>
			</el-table-column>

			<slot></slot>
			<template #empty>{{ placeholder }}</template>
		</el-table>
	</div>
</template>

<script>
import Sortable from "sortablejs";
import {formatMillennials} from "@/utils/util";
export default {
	inject: ["formTable"],
	props: {
		maxHeight: { type: [Number, String], default: "auto" },
		modelValue: { type: Array, default: () => [] },
		addTemplate: { type: Object, default: () => { } },
		placeholder: { type: String, default: "暂无数据" },
		dragSort: { type: Boolean, default: false },
		showRowAdd: { type: Boolean, default: true }, //是否显示新增行按钮
		showRowDel: { type: Boolean, default: true }, //是否显示删除行按钮
		dragEndEvent: { type: Function, default: null },
		isReadMode: { type: Boolean, default: false }, //只读模式，如为true  则不显示添加和删除按钮
		scrollbarAlways: { type: Boolean, default: false }, //总是显示滚动条
		showIndex: { type: Boolean, default: true },
		showSummary: { type: Boolean, default: false },
		cellStyle:{type:Function,default:()=>{}}
	},
	data() {
		return {
			data: [],
			toggleIndex: 0,
		};
	},
	mounted() {
		this.data = this.modelValue;
		if (this.dragSort) {
			this.rowDrop();
		}
	},
	computed:{
		getSummariesData(){
			if(this.formTable.widget.options.inPagination){
				return this.formTable.formModel[this.formTable.widget.options.name]
			}
			else{
				return this.data;
			}
		}
	},
	watch: {
		modelValue() {
			this.data = this.modelValue;
		},
		data: {
			handler() {
				this.$emit("update:modelValue", this.data);
			},
			deep: true,
		},
		dragSort() {
			if (this.dragSort) {
				this.rowDrop();
			}
		},
	},
	methods: {
		getSummaries(param) {
			let that = this
			const { columns, data } = param
			const sums = []

			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = "合计";
					return
				}
        const columnProps = this.formTable.widget.widgetList.find(
            (it) => it.options.name == column.property
        );
        if (!columnProps) {
          return;
        }
				if (columnProps.type == "inputNumber" && columnProps.options.millennials) {
					//console.log("千分位转换");
          const values = this.getSummariesData.map(
              (item) => item[column.property]
          );
          let sumMoney = 0;
          values.forEach((money) => {
            let value = money;
            if (isNaN(money)) {
              value = Number(money.replace(/,/g, ""));
            }
            sumMoney += Number(value);
          });
          if (sumMoney == 0) {
            sums[index] = "";
          } else {
            sums[index] = formatMillennials(sumMoney.toFixed(columnProps.options.precision));
          }
				}
				else {
					let values = this.getSummariesData.map((item) => Number(item[column.property]))
					if (!values.every((value) => Number.isNaN(value))) {
						sums[index] = `${values.reduce((prev, curr) => {
							const value = Number(curr)
							if (!Number.isNaN(value)) {
								return prev + curr
							} else {
								return prev
							}
						}, 0)}`
					} else {
						sums[index] = 'N/A'
					}
				}
				
			})
			return sums;
		},
		rowDrop() {
			const _this = this;
			const tbody = this.$refs.table.$el.querySelector(
				".el-table__body-wrapper tbody"
			);
			Sortable.create(tbody, {
				handle: ".move",
				animation: 300,
				ghostClass: "ghost",
				onEnd({ newIndex, oldIndex }) {
					const tableData = _this.data;
					const currRow = tableData.splice(oldIndex, 1)[0];
					tableData.splice(newIndex, 0, currRow);
					_this.toggleIndex += 1;
					_this.$nextTick(() => {
						_this.rowDrop();
					});
					if (!!_this.dragEndEvent) {
						_this.dragEndEvent(newIndex, oldIndex);
					}
				},
			});
		},
		rowAdd() {
			const temp = JSON.parse(JSON.stringify(this.addTemplate));
			this.data.push(temp);
		},
		rowDel(row, index) {
			this.data.splice(index, 1);
		},
		refreshLayout() {
			// 刷新表格显示，防止行列显示错位！！
			this.$refs.table.doLayout();
		},
    scrollToBottom() {
      this.$nextTick(() => {
        const tb = this.$refs.table.$refs.bodyWrapper.getElementsByClassName("el-scrollbar__wrap")[0];
        tb.scrollTop = tb.scrollHeight;
      });
    },
		getRef(){
			return this.$refs.table;
		}
	},
};
</script>

<style lang="scss" scoped>
.sc-form-table .sc-form-table-handle {
	text-align: center;
}

.sc-form-table :deep(.el-table__body .cell) {
  padding: 0 !important;
}

.sc-form-table {
  //:deep(.el-input__wrapper) {
  //  box-shadow: none;
  //}
  //
  //:deep(.el-input-number .el-input-number__decrease) {
  //  display: none;
  //}
  //
  //:deep(.el-input-number .el-input-number__increase) {
  //  display: none;
  //}
}

.sc-form-table .sc-form-table-handle span {
	display: inline-block;
}

.sc-form-table .sc-form-table-handle {
	:deep(button) {
		display: none;
	}
}

.sc-form-table .hover-row .sc-form-table-handle {
	span {
		display: none;
	}
}

.sc-form-table .hover-row .sc-form-table-handle {
	:deep(button) {
		display: inline-block;
	}
}

.sc-form-table .hover-row .sc-form-table-handle.sc-button {
	span {
		display: inline-block !important;
	}

	:deep(button) {
		display: none !important;
	}
}

</style>
